package cc.beup.common.util;

import cc.beup.common.constant.PlatformResponseCodeEnum;
import cc.beup.common.exception.PlatFormBizException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;


/**
 * @Author: Byron Bai
 * @Date: 2021/4/18 20:13
 * @Description: 校验工具类
 */
public class PlatFormValidator {

    private PlatFormValidator() {
    }

    private static final Validator VALIDATOR;

    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        VALIDATOR = factory.getValidator();
    }

    public static <T> void validate(T t) {
        Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(t);
        if (constraintViolations == null || constraintViolations.size() < 1) {
            return;
        }
        ConstraintViolation<T> constraintViolation = constraintViolations.stream().findFirst().get();
        throw new PlatFormBizException(constraintViolation.getMessage(), PlatformResponseCodeEnum.VALIDATION_ERROR.getCode());
    }


}
